package com.shurdroides.proyectofinal.map;

import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.Toast;


public class ProximityAlert {

	private static final long MINIMUM_DISTANCECHANGE_FOR_UPDATE = 1;
	private static final long MINIMUM_TIME_BETWEEN_UPDATE = 1000;
	private static final long POINT_RADIUS = 500;
	private static final long PROX_ALERT_EXPIRATION = -1;
	private static final String PROX_ALERT_INTENT = "com.shurdroides.proyectofinal.ProximityAlert";
	private LocationManager locationManager;
	private Context ctx;

	public ProximityAlert(Context ctx, double lat, double lon) {
		this.ctx = ctx;
		locationManager = (LocationManager) ctx
				.getSystemService(Context.LOCATION_SERVICE);
		locationManager.requestLocationUpdates(
				LocationManager.NETWORK_PROVIDER, MINIMUM_TIME_BETWEEN_UPDATE,
				MINIMUM_DISTANCECHANGE_FOR_UPDATE, new MyLocationListener());
		saveProximityAlertPoint();
	}

	private void saveProximityAlertPoint() {
		Location location = locationManager
				.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
		if (location == null) {
			Toast.makeText(ctx, "No last known location. Aborting...",
					Toast.LENGTH_LONG).show();
			return;
		}
		addProximityAlert(location.getLatitude(), location.getLongitude());
	}

	private void addProximityAlert(double latitude, double longitude) {

		Intent intent = new Intent(PROX_ALERT_INTENT);
		PendingIntent proximityIntent = PendingIntent.getBroadcast(ctx, 0,
				intent, 0);

		locationManager.addProximityAlert(latitude, longitude, POINT_RADIUS,
				PROX_ALERT_EXPIRATION, proximityIntent);

		IntentFilter filter = new IntentFilter(PROX_ALERT_INTENT);
		ctx.registerReceiver(new ProximityReceiver(), filter);

	}

	public class MyLocationListener implements LocationListener {
		public void onLocationChanged(Location location) {
		}

		public void onStatusChanged(String s, int i, Bundle b) {
		}

		public void onProviderDisabled(String s) {
		}

		public void onProviderEnabled(String s) {
		}
	}

}
